package com.csdj.t301.aop;

import com.alibaba.fastjson.JSONObject;
import com.csdj.t301.vo.WebResult;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;

/**
 * 拦截角色调用
 * author:cloud
 * date:2021/3/19 0019
 **/
@Aspect
@Component
public class RoleParser {

    /**
     * 通过注解来标记切入点
     */
    @Pointcut("@annotation(Role)")
    private void pointcut(){}


    @Around("pointcut()")
    public Object around(ProceedingJoinPoint pjp){
        //获取切入点的方法
        Method  method = ((MethodSignature)pjp.getSignature()).getMethod();
        Role role = method.getAnnotation(Role.class);
        String[] roles = role.value();
        if(!checkRole(roles)){
            //权限认证失败,不执行方法直接返回
            return null;
        }
        //通过权限认证
        try {
            //调用切入点的方法
            return pjp.proceed();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            return null;
        }
    }


    /**
     * 判断权限
     * @param roles
     * @return
     */
    private boolean checkRole(String[] roles){
        //权限判断结果
        boolean flag = false;
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        String role = (String) attributes.getRequest().getSession().getAttribute("role");
        if(role == null){
            flag = false;
        }else{
            //遍历注解中的权限要求
            for(String r:roles){
                if(r.equals(role)){
                    flag = true;
                    break;
                }
            }
        }
        if(!flag){
            WebResult result = new WebResult(403);
            result.setMsg("实力不允许！权限不够");
            //响应请求
            HttpServletResponse response = attributes.getResponse();
            response.setContentType("text/html;charset=utf-8");
            PrintWriter out = null;
            try {
                out = response.getWriter();
                out.write(JSONObject.toJSONString(result));
                out.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                out.close();
            }
        }
        return flag;
    }
}
